<?php
namespace lxs\config;

use App\Models\system\ConfigModel;

class System extends BaseStatic
{

    /**
     * 配置数据缓存
     * @var array
     */
    protected $data = [];


    /**
     * 设置配置数据
     * @param string $name 配置名称
     * @param string|array $value 配置内容
     * @return integer
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function set(string $name, string|array $value = ''): int
    {
        $this->data = [];
        [$type, $field] = $this->_parse($name, 'base');
        if (is_array($value)) {
            $count = 0;
            foreach ($value as $kk => $vv) {
                $count += $this->set("{$field}.{$kk}", $vv);
            }
            return $count;
        } else {
            $map = ['type' => $type, 'name' => $field];
            $data = array_merge($map, ['value' => $value]);
            $query = ConfigModel::where($map);
            return (clone $query)->count() > 0 ? $query->update($data) : $query->create($data);
        }
    }


    /**
     * 读取配置数据
     * @param string $name
     * @param string $default
     * @return array|mixed|string
     */
    public function get(string $name = '', string $default = ''): mixed
    {
        if (empty($this->data)) {
            ConfigModel::get()->map(function ($item) {
                $this->data[$item['type']][$item['name']] = $item['value'];
            });
        }
        [$type, $field, $outer] = $this->_parse($name);

        if ($type == '') {
            return $this->data[$field];
        }

        if (empty($name)) {
            return $this->data;
        } elseif (isset($this->data[$type])) {
            $group = $this->data[$type];
            if ($outer !== 'raw') foreach ($group as $kk => $vo) {
                $group[$kk] = htmlspecialchars($vo);
            }
            return $field ? ($group[$field] ?? $default) : $group;
        } else {
            return $default;
        }
    }


    /**
     * 解析缓存名称
     * @param string $rule 配置名称
     * @param string $type 配置类型
     * @return array
     */
    private function _parse(string $rule, string $type = ''): array
    {
        if (stripos($rule, '.') !== false) {
            [$type, $rule] = explode('.', $rule, 2);
        }
        [$field, $outer] = explode('|', "{$rule}|");
        return [$type, $field, strtolower($outer)];
    }

}
